<template>
	<div class="account">
		<div class="pwd-form">
			<el-dialog title="重置密码" :visible.sync="showChangePwd">
				<el-form :model="userInfo" status-icon :rules="pwdRules" ref="pwdForm" label-width="100px">
					<el-form-item label="新密码" prop="pass">
						<el-input type="password" v-model="userInfo.pass" autocomplete="off" show-password></el-input>
					</el-form-item>
					<el-form-item label="确认新密码" prop="checkPass">
						<el-input type="password" v-model="userInfo.checkPass" autocomplete="off" show-password></el-input>
					</el-form-item>
				</el-form>
				<div class="btns">
					<el-button @click="cancelPwd">取消</el-button>
					<el-button @click="changePwd" type="primary">确认</el-button>
				</div>
			</el-dialog>
		</div>
		<el-tabs v-model="activeName" @tab-click="changeUserTab">
			<el-tab-pane label="坐席管理" name="agent">
				<div class="head">
					<el-button type="primary" @click="addAgent">创建坐席</el-button>
				</div>
				<div class="table">
					<Table :tableData="agentData">
						<template v-slot:btn>
							<el-table-column width="440px" align="center" label="操作">
								<template slot-scope="scope">
									<el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
									<el-button size="mini" type="primary" @click="disableAgent(scope.$index, scope.row)">{{ scope.row.status === 'N' ? '失效' : '恢复' }}</el-button>
									<el-button size="mini" type="warning" @click="resetPwd(scope.$index, scope.row)" :disabled="scope.row.resetPwd">重置密码</el-button>
									<!-- <el-button size="mini" type="info" @click="viewGroupInfo(scope.$index, scope.row)">绑定分组</el-button> -->
									<el-button size="mini" type="info" @click="viewshowBindGroup(scope.$index, scope.row)">绑定分组</el-button>
									<el-button size="mini" type="success" @click="editProperty(scope.$index, scope.row)">编辑属性</el-button>
								</template>
							</el-table-column>
						</template>
					</Table>
				</div>
				<br />
				<div class="page">
					<PageSize :pages="checkAgent" @changePageSize="changeAgentPageSize" @changeCurrentPage="changeAgentCurrentPage" />
				</div>
			</el-tab-pane>
			<!-- <el-tab-pane label="用户管理" name="user">
				<div class="head">
					<el-button type="primary" @click="addUser">创建用户</el-button>
				</div>
				<div class="table">
					<Table :tableData="userData" @tableCellClick="modifyAvatar">
						<template v-slot:picture>
							<el-table-column width="100px" align="center" label="头像" attr="avatar">
								<template slot-scope="scope">
									<el-avatar size="50" :src="scope.row.userPicture" v-if="scope.row.userPicture"></el-avatar>
									<span v-else>暂无头像</span>
								</template>
							</el-table-column>
						</template>

						<template v-slot:btn>
							<el-table-column width="440px" align="center" label="操作">
								<template slot-scope="scope">
									<el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除</el-button>
									<el-button size="mini" type="primary" @click="disableUser(scope.$index, scope.row)">{{ scope.row.status === 'N' ? '失效' : '恢复' }}</el-button>
									<el-button size="mini" type="warning" @click="resetPwd(scope.$index, scope.row)" :disabled="scope.row.resetPwd">重置密码</el-button>
									<el-button size="mini" type="success" @click="modifyUser(scope.$index, scope.row)">修改用户信息</el-button>
								</template>
							</el-table-column>
						</template>
					</Table>
				</div>
				<br />
				<div class="page">
					<PageSize :pages="checkData" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage" />
				</div>
			</el-tab-pane> -->
		</el-tabs>
		<BindGroup
			:showBindGroup="showBindGroup"
			v-if="showBindGroup"
			:tableData="groupsSkill"
			@closeBindGroup="closeBindGroup"
			@addGroup="addGroupSkill"
			@removeGroup="removeGroupSkill"
			@edit="editGroupSkill"
			@save="save"
		>
		</BindGroup>
		<CheckGroupInfo
			:schedulingAttributes="schedulingAttributes"
			:showAddAgent="showAddAgent"
			:agentType="agentType"
			:showAddUser="showAddUser"
			:showModifyProp="showModifyProp"
			:showModifyUser="showModifyUser"
			:modifyUserData="modifyUserData"
			@addAttribute="addAttribute"
			@reomveProp="reomveProp"
			@createAgentProp="createAgentProp"
			@closeAddTips="closeAddTips"
			@cancelAddAgent="cancelAddAgent"
			@createAgent="createAgent"
			@changeAgnetType="changeAgnetType"
			@getModifyUser="getModifyUser"
			@closeAddUser="closeAddUser"
			@closeModifyProp="closeModifyProp"
			@createUser="createUser"
			@cancelCreateUser="closeAddUser"
			@closeModifyUser="closeModifyUser"
			@modifyPicSuccess="modifyPicSuccess"
		>
			<template v-slot:page>
				<el-pagination
					@size-change="changeGroupPageSize"
					@current-change="changeGroupCurrentPage"
					:current-page="checkGroup.page"
					:page-sizes="[10, 20, 30, 40]"
					:page-size="checkGroup.pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="checkGroup.total"
				>
				</el-pagination>
			</template>
		</CheckGroupInfo>
	</div>
</template>

<script>
import Table from '../components/Table.vue';
import PageSize from '../components/PageSize.vue';
import CheckGroupInfo from './CheckGroupInfo.vue';
import BindGroup from './BindGroup.vue';
import { isServing, getUserList, deleteAccount, updateAccountInfo, getAllGroups, getGroupWithUserId, accountRegister, updateRegister, saveGroupPriority } from '../../api/api';
import { mapState } from 'vuex';
import { validatePass, validatePassChecked } from '@/utils/formValidate';
import { validateCustomerUserName, validateCustomerRealName } from '@/utils/customerValidate';
export default {
	components: {
		Table,
		PageSize,
		CheckGroupInfo,
		BindGroup
	},
	data() {
		return {
			editAgentId: '',
			userLevelId: '',
			schedulingAttributes: [],
			activeName: 'agent',
			checkData: {
				page: 1,
				pageSize: 10,
				total: 0,
				role: 'agent'
			},
			checkAgent: {
				page: 1,
				pageSize: 10,
				total: 0,
				role: 'agent'
			},
			userInfo: {
				userId: '',
				pass: '',
				checkPass: ''
			},
			checkGroup: {
				page: 1,
				pageSize: 10,
				total: 0,
				userId: ''
			},
			pwdRules: {
				pass: [
					{ required: true, message: '请输入用户密码', trigger: ['blur', 'change'] },
					{ validator: validatePass, trigger: ['blur', 'change'] }
				],
				checkPass: [
					{ required: true, message: '请输入用户密码', trigger: ['blur', 'change'] },
					{ validator: validatePassChecked, trigger: ['blur', 'change'] }
				]
			},
			agentType: 0,
			showChangePwd: false,
			isvalidatePwd: false,
			showAddAgent: false,
			showModifyGroup: false,
			showModifyProp: false,
			showAddUser: false,
			showModifyUser: false,
			agentData: {
				sort: false,
				tableHead: [
					{
						label: '用户名',
						prop: 'userName'
					},
					{
						label: '机构',
						prop: 'userOrg'
					},
					{
						label: '账户状态',
						prop: 'isDisabled'
					},
					{
						label: '是否机器人',
						prop: 'isRobot'
					}
				],
				tableConent: [],
				showIndex: false
			},
			userData: {
				sort: false,
				tableHead: [
					{
						label: '用户名',
						prop: 'userName'
					},
					{
						label: '机构',
						prop: 'userOrg'
					},
					{
						label: '用户等级',
						prop: 'userLevel'
					},
					{
						label: '真实姓名',
						prop: 'realName'
					},
					{
						label: '性别',
						prop: 'gender'
					},
					{
						label: '账户状态',
						prop: 'isDisabled'
					}
				],
				tableConent: [],
				showIndex: false
			},
			groupList: [],
			modifyUserData: {
				submitProp: {
					userName: '',
					realName: '',
					gender: '',
					userLevel: '',
					picture: ''
				},
				genderOptions: [
					{ gender: 'male', label: '男' },
					{ gender: 'female', label: '女' }
				],
				userNameRules: [
					{ required: true, message: '请输入用户名', trigger: ['blur', 'change'] },
					{ validator: validateCustomerUserName, trigger: ['blur', 'change'] }
				],
				realNameRules: [
					{ required: true, message: '请输入真实姓名', trigger: ['blur', 'change'] },
					{ validator: validateCustomerRealName, trigger: ['blur', 'change'] }
				],
				requireRules: [{ required: true, message: '请选择性别', trigger: 'change' }],
				userLevelRules: [
					{ required: true, message: '请输入用户等级', trigger: ['blur', 'change'] },
					{ type: 'number', min: 1, max: 100, message: '格式错误，用户等级为1~100以内的数字，不可为空', trigger: ['blur', 'change'] }
				],
				userPic: [{ required: true, message: '请输入用户名', trigger: ['blur', 'change'] }]
			},
			showBindGroup: false,
			// 并发分组
			groupsSkill: {
				showNo: false,
				showCheck: false,
				isEdit: true,
				tableHead: [
					{
						label: '技能组名称',
						prop: 'name'
					},
					{
						label: '组内权重',
						prop: 'weight'
					},
					{
						label: '多组并发权重',
						prop: 'groupPriority'
					},
					{
						label: '是否组长',
						prop: 'isChief'
					}
				],
				tableConent: [],
				options: [
					{
						value: '10',
						label: '技能组1'
					},
					{
						value: '20',
						label: '技能组2'
					},
					{
						value: '30',
						label: '技能组3'
					},
					{
						value: '40',
						label: '技能组4'
					},
					{
						value: '50',
						label: '技能组5'
					}
				]
			},
			// 默认并发组数据
			defaultGroupSkill: {
				name: {
					value: '',
					label: '',
					isSet: true,
					isEmpty: false,
					isRepeats: false
				},
				weight: {
					value: 1,
					isSet: true,
					invalid: false
				},
				isChief: {
					value: false,
					isSet: true,
					invalid: false
				},
				groupPriority: {
					value: 1,
					isSet: true,
					invalid: false
				}
			},
			// 接口返回分组信息，用于筛选 id
			groupsSkillData: []
		};
	},
	computed: {
		...mapState({
			loginInfo: state => state.login.userInfo
		})
	},
	mounted() {
		this.getUserListInit();
		this.getAllGroupInit();
	},

	methods: {
		getAllGroupInit() {
			getAllGroups().then(res => {
				this.groupsSkill.options = res.data;
			});
		},

		// 用户、坐席 tab标签
		changeUserTab(tab) {
			if (tab.name === 'user') {
				this.checkData.role = 'customer';
				this.getUserListInit();
			} else {
				this.checkData.role = 'agent';
				this.getUserListInit();
			}
		},
		// 用户数据分页
		changeAgentPageSize(val) {
			this.checkAgent.role = 'agent';
			this.checkAgent.pageSize = val;
			this.checkAgent.page = 1;
			this.getAgentListInit();
			// console.warn('changeAgentPageSize', val, this.checkAgent);
		},
		changeAgentCurrentPage(val) {
			this.checkAgent.role = 'agent';
			this.checkAgent.page = val;
			this.getAgentListInit();
			// console.log(val, 'changeAgentCurrentPage:', this.checkAgent);
		},

		changePageSize(val) {
			this.checkData.role = 'customer';
			this.checkData.pageSize = val;
			this.checkData.page = 1;
			this.getUserListInit();
			// console.warn('changeCustomerPageSize', val, this.checkData);
		},
		changeCurrentPage(val) {
			this.checkData.role = 'customer';
			this.checkData.page = val;
			this.getUserListInit();
			// console.log(val, 'changeCustomerPage', this.checkData);
		},

		// 用户分组分页
		changeGroupPageSize(val) {
			this.checkGroup.pageSize = val;
			this.getGroupWithUserIdInit();
		},
		changeGroupCurrentPage(val) {
			this.checkGroup.page = val;
			this.getGroupWithUserIdInit();
		},
		// 新增座席
		addAgent() {
			this.showAddAgent = true;
		},
		createAgent(info) {
			let data = {};
			data.name = info.userName;
			data.org = this.loginInfo.org;
			data.role = 'agent';
			if (this.agentType === 1) {
				data.pwd = 'zealcomm@ivcs_robot2021';
				data.isRobot = true;
				data.profile = {
					isRobot: true
				};
			} else {
				data.pwd = info.pass;
				data.isRobot = false;
				data.profile = {
					isRobot: false
				};
			}
			accountRegister(data)
				.then(res => {
					if (res.status === 200) {
						this.$message.success('创建坐席成功！');
						this.showAddAgent = false;
						this.getUserListInit();
					}
				})
				.catch(err => {
					this.$Spin.hide();
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		changeAgnetType(type) {
			this.agentType = Number(type);
		},
		cancelAddAgent() {
			this.showAddAgent = false;
		},
		closeAddTips() {
			this.showAddAgent = false;
		},

		// 创建用户
		addUser() {
			this.showAddUser = true;
		},
		createUser(val) {
			let data = { profile: {} };
			data.customerLevel = val.userLevel;
			data.org = this.loginInfo.org;
			data.profile.fullName = val.realName;
			data.profile.gender = val.gender;
			data.profile.picture = val.picture;
			data.pwd = val.pass;
			data.role = 'customer';
			data.name = val.userName;
			console.log(data);
			accountRegister(data)
				.then(res => {
					if (res.status === 200) {
						this.$message.success('创建用户成功！');
						this.getUserListInit();
						this.showAddUser = false;
					}
				})
				.catch(err => {
					if (err.code === '1002') {
						this.$message.error('创建用户失败，用户已存在！');
					} else {
						this.$message.error(`创建用户失败，${err.message}`);
					}
				});
		},
		closeAddUser() {
			this.showAddUser = false;
		},

		/**
		 * 判断坐席是否在通话中
		 * @param {int} userId
		 */
		isServing(userId) {
			console.log('isServing user', userId);
			return new Promise((resolve, reject) => {
				isServing(userId)
					.then(resp => {
						console.log('isServingUser data', resp.data);
						if (resp && resp.data && resp.data.code === 200) {
							if (resp.data.data.isServing) {
								resolve(1);
							} else {
								resolve(0);
							}
						} else {
							resolve(0);
						}
					})
					.catch(e => {
						reject(e);
					});
			});
		},

		// 删除用户
		async deleteUser(index, row) {
			console.log('deleteUser user', row, index);
			try {
				const subtitle = row.role === 'agent' ? `确定要删除坐席 <${row.userName}> 吗, 是否继续?` : `确定要删除用户 <${row.userName}> 吗, 是否继续?`;
				if (row.role === 'agent') {
					this.$Spin.show();
					const isServingUser = await this.isServing(row.userId);
					console.log('isServingUser', isServingUser);
					this.$Spin.hide();
					if (isServingUser) {
						this.$confirm(`确定要删除坐席 <${row.userName}> 吗, 该坐席正在通话中，将会强制结束会话，是否继续?`, '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						})
							.then(async () => {
								await this.deleteAccount(row.userId);
								this.$message({
									type: 'success',
									message: '删除成功!'
								});
							})
							.catch(() => {
								this.$message({
									type: 'info',
									message: '已取消'
								});
							});
					} else {
						this.$confirm(subtitle, '提示', {
							confirmButtonText: '确定',
							cancelButtonText: '取消',
							type: 'warning'
						})
							.then(async () => {
								await this.deleteAccount(row.userId);
								this.$message({
									type: 'success',
									message: '删除成功!'
								});
							})
							.catch(() => {
								this.$message({
									type: 'info',
									message: '已取消'
								});
							});
					}
				} else {
					this.$confirm(subtitle, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
						.then(async () => {
							await this.deleteAccount(row.userId);
							this.$message({
								type: 'success',
								message: '删除成功!'
							});
						})
						.catch(() => {
							this.$message({
								type: 'info',
								message: '已取消'
							});
						});
				}
			} catch (error) {
				this.$Spin.hide();
				this.$message.error('删除失败！');
			}
		},

		/**
		 * 根据userId删除账号
		 * @param {int} userId
		 */
		deleteAccount(userId) {
			return new Promise((resolve, reject) => {
				deleteAccount(userId)
					.then(res => {
						if (res.status === 200) {
							this.getUserListInit();
							resolve('ok');
						}
					})
					.catch(err => {
						reject(err);
					});
			});
		},

		// 失效用户
		disableUser(index, row) {
			this.$confirm(`确定要${row.status === 'N' ? '失效' : '恢复'}用户 ${row.userName} 吗, 是否继续?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					let params = [
						{ op: 'replace', path: '/isDisabled', value: row.status === 'N' ? 'Y' : 'N' } // 设置该用户是否失效   Y/失效  N/没有失效
					];
					let data = {};
					data.params = params;
					data.userId = row.userId;
					updateAccountInfo(data)
						.then(res => {
							if (res.status === 200) {
								this.getUserListInit();
								this.$message({
									type: 'success',
									message: `${row.status === 'N' ? '失效' : '恢复'}成功!`
								});
							}
						})
						.catch(err => {
							this.$message({
								type: 'error',
								message: `${row.status === 'N' ? '失效' : '恢复'}失败！${err}`
							});
						});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					});
				});
		},

		// 重置密码
		resetPwd(index, row) {
			this.isvalidatePwd = false;
			this.showChangePwd = true;
			this.userInfo.userId = row.userId;
		},
		// 修改用户
		modifyUser(index, row) {
			console.log(row);
			this.modifyUserData.submitProp.userLevel = row.userLevel;
			this.modifyUserData.submitProp.userName = row.userName;
			this.modifyUserData.submitProp.realName = row.realName;
			this.modifyUserData.submitProp.picture = row.userPicture;
			this.modifyUserData.submitProp.gender = row.gender;
			this.userId = row.userId;
			this.showModifyUser = true;
		},
		modifyPicSuccess(file) {
			console.log(file);
			if (file.code === 200) {
				this.modifyUserData.submitProp.picture = file.data.url;
			} else {
				this.$message.error('头像上传失败');
				this.modifyUserData.submitProp.picture = '';
			}
		},

		closeModifyUser() {
			this.showModifyUser = false;
		},

		cancelPwd() {
			this.showChangePwd = false;
			this.userInfo.pass = '';
			this.userInfo.checkPass = '';
			this.validatePwd = false;
			this.$refs.pwdForm.resetFields();
		},
		changePwd() {
			this.$refs['pwdForm'].validate(valid => {
				if (valid) {
					const params = [
						{ op: 'replace', path: '/pwd', value: this.userInfo.pass } // 设置该用户是否失效   Y/失效  N/没有失效
					];
					const data = {};
					data.params = params;
					data.userId = this.userInfo.userId;
					updateAccountInfo(data)
						.then(() => {
							this.$message.success('重置密码成功！');
						})
						.catch(err => {
							this.$Spin.hide();
							this.$requestApiError(err, () => {
								this.$router.push('/');
							});
						});
					this.showChangePwd = false;
					this.$refs.pwdForm.resetFields();
				}
			});
		},
		// 绑定分组
		viewshowBindGroup(index, row) {
			this.showBindGroup = true;
			this.checkGroup.page = 1;
			this.checkGroup.pageSize = 10;
			this.checkGroup.userId = row.userId;
			this.groupsSkill.tableConent = [];
			this.groupsSkill.isEdit = true;
			console.log(this.groupsSkill.tableConent);
			this.getGroupWithUserIdInit();
		},
		// 关闭绑定分组对话框
		closeBindGroup() {
			this.groupsSkill.tableConent = [];
			this.showBindGroup = false;
		},
		// 编辑分组,初始化编辑状态
		editGroupSkill() {
			this.groupsSkill.isEdit = false;
			if (this.groupsSkill.tableConent.length === 0) {
				this.groupsSkill.tableConent.push({
					name: {
						value: '',
						label: '',
						isSet: true,
						isEmpty: false,
						isRepeats: false
					},
					weight: {
						value: 1,
						isSet: true,
						invalid: false
					},
					isChief: {
						value: false,
						isSet: true
					},
					groupPriority: {
						value: 1,
						isSet: true,
						invalid: false
					}
				});
			}
			this.groupsSkill.tableConent.forEach(item => {
				item.name.isSet = true;
				item.weight.isSet = true;
				item.isChief.isSet = true;
				item.groupPriority.isSet = true;
			});
		},
		// 保存分组
		save() {
			let submitData = [];
			let repeats = [];
			let flag = false;
			for (let i = 0; i < this.groupsSkill.tableConent.length; i++) {
				let groupId = this.groupsSkill.tableConent[i].name.value;
				let weight = this.groupsSkill.tableConent[i].weight.value;
				let groupPriority = this.groupsSkill.tableConent[i].groupPriority.value;
				// 校验值合法性
				if (groupId === '') {
					this.groupsSkill.tableConent[i].name.isEmpty = true;
					flag = true;
				} else {
					this.groupsSkill.tableConent[i].name.isEmpty = false;
				}
				if (Number(weight) > 99 || Number(weight) < 1 || !new RegExp('^[0-9]+$', 'g').test(weight)) {
					this.groupsSkill.tableConent[i].weight.invalid = true;
					flag = true;
				} else {
					this.groupsSkill.tableConent[i].weight.invalid = false;
				}
				if (Number(groupPriority) > 99 || Number(groupPriority) < 1 || !new RegExp('^[0-9]+$', 'g').test(groupPriority)) {
					this.groupsSkill.tableConent[i].groupPriority.invalid = true;
					flag = true;
				} else {
					this.groupsSkill.tableConent[i].groupPriority.invalid = false;
				}
				// 去重
				if (repeats.indexOf(groupId) !== -1) {
					this.groupsSkill.tableConent[i].name.isRepeats = true;
					this.groupsSkill.tableConent[i].name.isSet = true;
					flag = true;
				} else {
					repeats.push(groupId);
					this.groupsSkill.tableConent[i].name.isRepeats = false;
					if (!flag) {
						let obj = {};
						obj.groupId = groupId;
						obj.name = this.groupsSkill.tableConent[i].name.label;
						obj.isChief = Boolean(this.groupsSkill.tableConent[i].isChief.value);
						obj.weight = Number(weight);
						obj.groupPriority = Number(groupPriority);
						// 取出修改元素 id
						let ids = this.groupsSkillData.filter(item => item.groupId === groupId);
						obj.id = ids.length > 0 ? ids[0].id : '';
						submitData.push(obj);
						// 存储数据
						console.log(submitData);
					}
				}
			}
			if (!flag) {
				saveGroupPriority(submitData, this.checkGroup.userId)
					.then(res => {
						if (res.status === 200) {
							this.$message.success('保存技能分组成功！！！');
							this.getGroupWithUserIdInit();
							this.groupsSkill.isEdit = true;
						}
					})
					.catch(err => {
						if (err.code === '1301' && err.data.errCode === 1) {
							this.$message.error(`该技能组所属业务没有绑定AI工作流，请先为业务场景<${err.data.msg}>绑定AI工作流！`);
						} else {
							this.$message.error('保存技能分组失败！！！');
						}
						this.getGroupWithUserIdInit();
					});
				this.showBindGroup = false;
			}
		},
		// 增加技能组
		addGroupSkill() {
			let obj = {};
			obj = JSON.parse(JSON.stringify(this.defaultGroupSkill));
			this.groupsSkill.tableConent.push(obj);
		},

		// 删除分组
		removeGroupSkill(scope) {
			this.groupsSkill.tableConent.splice(scope.$index, 1);
		},

		// 编辑坐席属性
		editProperty(index, row) {
			this.showModifyProp = true;
			this.schedulingAttributes = row.schedulingAttributes ? row.schedulingAttributes : [];
			this.editAgentId = row.userId;
		},
		// 添加属性，别删
		addAttribute() {
			let obj = {
				key: '',
				value: ''
			};
			this.schedulingAttributes.push(obj);
		},
		reomveProp(index) {
			this.schedulingAttributes.splice(index, 1);
		},
		closeModifyProp() {
			this.schedulingAttributes = [];
			this.showModifyProp = false;
		},
		createAgentProp() {
			if (this.schedulingAttributes.length === 0) {
				this.$message.error('请添加属性！');
				return;
			}
			let params = [
				{
					op: 'replace',
					path: '/schedulingAttributes',
					value: this.schedulingAttributes
				}
			];
			let data = {};
			data.params = params;
			data.userId = this.editAgentId;
			this.checkGroup.userId = this.editAgentId;
			updateAccountInfo(data).then(res => {
				if (res.status === 200) {
					this.$message.success('属性更新成功！');
					this.getGroupWithUserIdInit();
					this.getAgentListInit();
					this.showModifyProp = false;
				}
			});
		},
		getModifyUser() {
			console.log(this.modifyUserData.submitProp);
			let data = {
				profile: {
					fullName: '',
					gender: '',
					picture: ''
				}
			};
			data.userName = this.modifyUserData.submitProp.userName;
			data.userId = this.userId;
			data.customerLevel = this.modifyUserData.submitProp.userLevel;
			data.profile.fullName = this.modifyUserData.submitProp.realName;
			data.profile.gender = this.modifyUserData.submitProp.gender;
			data.profile.picture = this.modifyUserData.submitProp.picture;
			updateRegister(data)
				.then(res => {
					if (res.status === 200) {
						this.$message.success('用户信息修改成功！');
						this.showModifyUser = false;
						this.getUserListInit();
					}
				})
				.catch(err => {
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},

		// 密码校验
		validatePwdFn(rule, value, callback) {
			if (value === '') {
				return callback(new Error('请输入密码'));
			}
			if (this.userInfo.checkPass !== '') {
				this.$refs.pwdForm.validateField('checkPass');
			}
			return callback();
		},
		validatePwd2Fn(rule, value, callback) {
			if (value === '') {
				return callback(new Error('请再次输入密码'));
			} else if (value !== this.userInfo.pass) {
				return callback(new Error('两次输入密码不一致!'));
			}
			this.isvalidatePwd = true;
			return callback();
		},

		// API 方法初始化
		getUserListInit() {
			console.log('checkData', this.checkData);
			getUserList(this.checkData)
				.then(res => {
					if (res.status === 200) {
						this.checkAgent.total = res.data.data.count;
						this.checkData.total = res.data.data.count;
						const { data } = res.data.data;
						this.agentData.tableConent = data.map(item => {
							return {
								userId: item.id,
								userName: item.userName,
								userOrg: item.org,
								status: item.isDisabled,
								isDisabled: item.isDisabled === 'N' ? '有效' : '失效',
								isRobot: item.isRobot ? '是' : '否',
								resetPwd: item.isRobot,
								userLevel: item.customerLevel,
								realName: item.profile.fullName,
								gender: item.profile.gender === 'male' ? '男' : '女',
								userPicture: item.profile.picture,
								schedulingAttributes: item.schedulingAttributes,
								role: item.role
							};
						});
						this.userData.tableConent = this.agentData.tableConent;
					}
				})
				.catch(err => {
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		getAgentListInit() {
			this.$Spin.show();
			getUserList(this.checkAgent)
				.then(res => {
					if (res.status === 200) {
						this.checkAgent.total = res.data.data.count;
						const { data } = res.data.data;
						this.agentData.tableConent = data.map(item => {
							return {
								userId: item.id,
								userName: item.userName,
								userOrg: item.org,
								status: item.isDisabled,
								isDisabled: item.isDisabled === 'N' ? '有效' : '失效',
								isRobot: item.isRobot ? '是' : '否',
								resetPwd: item.isRobot,
								userLevel: item.customerLevel,
								realName: item.profile.fullName,
								gender: item.profile.gender === 'male' ? '男' : '女',
								userPicture: item.profile.picture,
								schedulingAttributes: item.schedulingAttributes,
								role: item.role
							};
						});
						this.userData.tableConent = this.agentData.tableConent;
						this.$Spin.hide();
					}
				})
				.catch(err => {
					this.$Spin.hide();
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		getGroupWithUserIdInit() {
			getGroupWithUserId(this.checkGroup)
				.then(res => {
					this.checkGroup.total = res.data.count;
					console.log(res.data);
					const { data } = res.data;
					this.groupsSkillData = data;
					if (data.length > 0) {
						this.groupsSkill.tableConent = data.map(item => {
							return {
								name: {
									value: item.groupId,
									label: item.group.name,
									isRepeats: false,
									isEmpty: false,
									isSet: false
								},
								weight: {
									value: item.weight,
									isSet: false,
									invalid: false
								},
								isChief: {
									value: item.isChief !== 0,
									isSet: false,
									invalid: false
								},
								groupPriority: {
									value: item.groupPriority ? item.groupPriority : 1,
									isSet: false,
									invalid: false
								}
							};
						});
					}
				})

				.catch(err => {
					this.$Spin.hide();
					this.$requestApiError(err, () => {
						this.$router.push('/');
					});
				});
		},
		// 失效坐席
		disableAgent(index, row) {
			console.warn('disableAgent:', index, row);
			this.$confirm(`确定要${row.status === 'N' ? '失效' : '恢复'}用户 ${row.userName} 吗, 是否继续?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					let params = [
						{ op: 'replace', path: '/isDisabled', value: row.status === 'N' ? 'Y' : 'N' } // 设置该用户是否失效   Y/失效  N/没有失效
					];
					let data = {};
					data.params = params;
					data.userId = row.userId;
					updateAccountInfo(data)
						.then(res => {
							if (res.status === 200) {
								this.getAgentListInit();
								this.$message({
									type: 'success',
									message: `${row.status === 'N' ? '失效' : '恢复'}成功!`
								});
							}
						})
						.catch(err => {
							this.$message({
								type: 'error',
								message: `${row.status === 'N' ? '失效' : '恢复'}失败！${err}`
							});
						});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					});
				});
		}
	}
};
</script>

<style lang="less">
.account {
	.btns {
		text-align: right;
	}
	.head {
		padding: 20px 0;
	}
	.el-avatar > img {
		width: 100%;
	}
}
</style>
